package com.furioussnails.sourcecodeanalysis.config;

import com.furioussnails.sourcecodeanalysis.pojo.Configuration;
import com.furioussnails.sourcecodeanalysis.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 封装sql
     * @param inputStream
     * @throws DocumentException
     */
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("/mapper/select");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String paramType = element.attributeValue("paramType");
            String resultType = element.attributeValue("resultType");
            String sqlText = element.getTextTrim();
            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            mapperStatement.setParamType(paramType);
            mapperStatement.setResultType(resultType);
            mapperStatement.setSqlText(sqlText);
            String key = namespace + "." + id;
            configuration.getMapperStatementMap().put(key,mapperStatement);
        }
    }
}
